package com.zzz.offer.findMedianSortedArrays;

public class Solution {

    public static void main(String[] args) {
        //int x = 5;
        //System.out.println((double) x / 2);
        System.out.println(findMedianSortedArrays(new int[] {1, 2}, new int[] {3, 4}));
    }

    public static double findMedianSortedArrays(int[] nums1, int[] nums2) {
        int len1 = nums1.length;
        int len2 = nums2.length;

        int total = len1 + len2;

        if(total==0) {
            return  0;
        }

        int[] merge = new int[total];

        int num1Index = 0;
        int num2Index = 0;
        for(int i = 0; i< total; i++) {
            if(num1Index == len1 && num2Index < len2) {
                merge[i] = nums2[num2Index];
                num2Index ++;
                continue;
            }

            if(num2Index == len2 && num1Index < len1) {
                merge[i] = nums1[num1Index];
                num1Index ++;
                continue;
            }

            if(nums1[num1Index] <= nums2[num2Index]) {
                merge[i] = merge[i] = nums1[num1Index];
                num1Index ++;
            } else {
                merge[i] = nums2[num2Index];
                num2Index ++;
            }
        }

        if(total == 1) {
            return merge[0];
        }

        if(total % 2 == 0) {
            int x = (merge[total/2 -1] + merge[total/2]);
            return  ( (double) x / 2);
        }

        return merge[total/2];
    }
}
